<template>
  <div id="createDialog">
    <el-dialog
      class="about-set"
      :title="showTitle"
      :visible.sync="dialogData.isShow"
      width="650px"
      :before-close="labelHandleClose"
    >
      <div class="form-box">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="90px"
          class="demo-ruleForm"
        >
          <el-form-item label="触达时间" prop="touchTime">
            <el-date-picker
              v-model="ruleForm.touchTime"
              type="datetime"
              placeholder="选择日期时间"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            label="触达通道"
            style="width: 52%;"
            label-width="90px"
            prop="touchType"
          >
            <el-select v-model="ruleForm.touchType" placeholder="请选择">
              <el-option
                v-for="item in touchTypeList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <template
            v-if="
              ruleForm.touchType === 'PUSH' || ruleForm.touchType === 'NOTICE'
            "
          >
            <el-form-item
              label-width="90px"
              :label="ruleForm.touchType === 'PUSH' ? '推送标题' : '站内信标题'"
              prop="title"
            >
              <el-input
                v-model="ruleForm.title"
                maxlength="20"
                show-word-limit
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <el-form-item
              label-width="90px"
              :label="ruleForm.touchType === 'PUSH' ? '推送内容' : '站内信内容'"
              prop="content"
            >
              <el-input
                v-model="ruleForm.content"
                type="textarea"
                rows="3"
                maxlength="50"
                show-word-limit
                placeholder="请输入"
                resize="none"
              ></el-input>
            </el-form-item>
          </template>
          <template v-else-if="ruleForm.touchType === 'BOMB_SCREEN'">
            <el-form-item label="显示终端" prop="displayTerminals">
              <el-radio-group v-model="ruleForm.displayTerminals">
                <el-radio
                  v-for="item in terminalTypeList"
                  :key="item.dictValue"
                  :label="item.dictValue"
                >
                  {{ item.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="弹屏图片" prop="img">
              <el-upload
                class="notice-uploader"
                :limit="1"
                action="#"
                accept=".jpg,.gif,.png"
                :show-file-list="true"
                :auto-upload="false"
                :on-change="changeUpload"
                :on-remove="handleRemove"
              >
                <img v-if="ruleForm.img" :src="ruleForm.img" class="notice" />
                <i v-else class="el-icon-plus notice-uploader-icon"></i>
              </el-upload>
              <div class="el-upload__tip">
                尺寸要求：330*330，JPG、GIF、PNG格式
              </div>
            </el-form-item>
            <el-form-item
              v-if="ruleForm.displayTerminals === 'APP'"
              prop="radioType"
            >
              <el-radio
                v-for="item in radioList"
                :key="item.labelValue"
                v-model="ruleForm.radioType"
                :label="item.labelValue"
                >{{ item.labelName }}</el-radio
              >
            </el-form-item>
          </template>
          <template v-else-if="ruleForm.touchType === 'SMS'">
            <el-form-item label="推送内容" prop="content">
              <el-input
                v-model="ruleForm.content"
                type="textarea"
                rows="3"
                maxlength="50"
                show-word-limit
                placeholder="请输入"
                resize="none"
              ></el-input>
            </el-form-item>
          </template>
          <div v-if="ruleForm.radioType === 'XCX'">
            <el-form-item label="ID" prop="appletId">
              <el-input v-model="ruleForm.appletId" clearable />
            </el-form-item>
          </div>
          <el-form-item v-else label="跳转链接" prop="url">
            <el-input v-model="ruleForm.url" placeholder="https://"></el-input>
            <template v-if="showTip">
              <p class="actionRed">
                注意：消息{{ tipText }}是收费项目，{{
                  tipText
                }}将会产生实际费用！
              </p>
            </template>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" plain @click="cancelLabel">取 消</el-button>
        <el-button
          type="success"
          :loading="loading"
          @click="confirmLabel('ruleForm')"
          >确认</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getNoticeDetailAPI,
  addEditRequestAPI
} from '@/api/noticeManagement/noticeManage'
import { sysNormalDisable } from '@utils/dictionariesFunc'
import { uploadImg } from '@/api/common/img'
export default {
  name: 'CreateDialog',
  msg: '通知管理-添加消息通知',
  components: {},
  props: ['dialogData', 'touchTypeList'],
  data() {
    return {
      showTitle: '',
      loading: false,
      eidtInitial: false, //编辑初始化赋值
      firstIn: false, //是否第一次进入（radioType）
      ruleForm: {
        touchTime: '', // 触达消息
        touchType: 'PUSH', // 触达通道
        title: '', // 推送标题
        content: '', // 推送内容
        url: '', // 跳转链接
        img: '', // 弹屏图片
        displayTerminals: [], //显示终端
        user: {
          name: ''
        },
        radioType: '', //详情链接/小程序
        appletId: '' //ID
      },
      // 显示终端
      terminalTypeList: [],
      tipText: '', //提示语
      rules: {
        touchTime: [{ required: true, message: '请输入时间', trigger: 'blur' }],
        touchType: [{ required: true, message: '请选择', trigger: 'blur' }],
        title: [{ required: true, message: '长度在20个字符', trigger: 'blur' }],
        content: [
          { required: true, message: '长度在50个字符', trigger: 'blur' }
        ],
        img: [{ required: true, message: '请选择图片', trigger: 'blur' }],
        displayTerminals: [
          { required: true, message: '请选择显示终端', trigger: 'blur' }
        ],
        radioType: [],
        appletId: []
      },
      noticeId: '', // 通知ID
      type: '', // add新增 edit编辑
      uploadImg: '',
      radioList: [
        { labelName: '详情链接', labelValue: 'URL' },
        { labelName: '小程序', labelValue: 'XCX' }
      ]
    }
  },
  computed: {
    showTip() {
      //显示条件：触达通道-“短信”、“推送”
      let touchType = this.ruleForm.touchType
      if (touchType === 'SMS') {
        this.tipText = '短信'
      }
      if (touchType === 'PUSH') {
        this.tipText = '推送'
      }
      return touchType === 'SMS' || touchType === 'PUSH'
    }
  },
  watch: {
    'ruleForm.touchType': {
      handler(newV, oldV) {
        if (this.eidtInitial) {
          this.eidtInitial = false
          return
        }
        //改变触达通道，内容清空
        this.ruleForm.title = ''
        this.ruleForm.img = ''
        this.ruleForm.displayTerminals = ''
        this.ruleForm.content = ''
      },
      deep: true
    },
    'ruleForm.displayTerminals': {
      handler(newV, oldV) {
        if (newV === 'APP') {
          if (this.firstIn) {
            this.firstIn = false
          } else {
            this.ruleForm.radioType = 'URL'
          }
        } else {
          this.ruleForm.radioType = ''
        }
      },
      deep: true
    }
  },
  mounted() {
    this.type = this.dialogData.type
    this.getStatusList()
    this.showTitle = this.type === 'add' ? '添加消息通知' : '修改消息通知'
    this.noticeId = this.dialogData.noticeId
    if (this.dialogData.noticeId && this.dialogData.type === 'edit') {
      this.getNoticeDetail()
    }
  },
  methods: {
    async getStatusList() {
      // 显示终端
      let data = await sysNormalDisable('pop_screen_terminal')
      this.terminalTypeList = this.terminalTypeList.concat(data)
    },
    labelHandleClose(done) {
      this.cancelLabel()
      done()
    },
    cancelLabel() {
      // 关闭前清空
      this.loading = false
      this.dialogData.isShow = false
    },
    changeUpload(file, fileList) {
      this.uploadImg = file.raw
      let formData = new FormData()
      formData.append('file', this.uploadImg)
      uploadImg(
        formData,
        (response) => {
          this.ruleForm.img = response[0].url
        },
        (response) => {
          this.$message.warning(response.message)
        }
      )
    },
    // 移除图片
    handleRemove(file, fileList) {
      this.ruleForm.img = ''
    },
    /* 确认提交 */
    confirmLabel(formName) {
      let _this = this
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return
        }
        let touchType = this.ruleForm.touchType
        if (touchType === 'SMS' || touchType === 'PUSH') {
          //“短信”、“推送”为收费项目
          this.$confirm(
            `<span style="color:red;font-weight:bold;">消息${this.tipText}是收费项目，${this.tipText}将会产生实际费用！ 确定要使用 "${this.tipText}" 方式发布通知吗？</span>`,
            '系统提示',
            {
              dangerouslyUseHTMLString: true,
              confirmButtonText: '我确认',
              cancelButtonText: '我再想想',
              type: 'warning'
            }
          ).then(() => {
            this.subForm()
          })
        } else {
          this.subForm()
        }
      })
    },
    // 提交
    subForm() {
      // let user = JSON.parse(sessionStorage.getItem('userInfo'))
      let user = JSON.parse(localStorage.getItem('userInfo'))
      if (user) {
        this.ruleForm.user = {
          name: user.userName
        }
      }
      let params = { ...this.ruleForm }
      delete params.radioType
      params.displayTerminals =
        params.displayTerminals && params.displayTerminals.length > 0
          ? [params.displayTerminals]
          : []
      if (this.ruleForm.radioType === 'XCX') {
        params.url = ''
      } else {
        params.appletId = ''
      }
      addEditRequestAPI(
        this.type,
        this.noticeId,
        params,
        (response) => {
          this.$emit('refresh')
          this.dialogData.isShow = false
        },
        (response) => {
          this.$message({
            message: response.message,
            type: 'warning'
          })
          this.dialogData.isShow = false
        }
      )
    },
    // 获取通知详情
    getNoticeDetail() {
      this.eidtInitial = true
      getNoticeDetailAPI(
        this.noticeId,
        (response) => {
          let obj = { ...response }
          //radioType赋值
          obj.radioType = response.appletId ? 'XCX' : 'URL'
          this.ruleForm = obj
          //字符串转数组
          let termimal = response.displayTerminals[0]
          this.ruleForm.displayTerminals = termimal
          if (termimal === 'APP') {
            this.firstIn = true
          }
        },
        (response) => {
          this.$message({
            message: response.message,
            type: 'warning'
          })
        }
      )
    }
  }
}
</script>

<style lang="less">
#createDialog {
  .el-autocomplete {
    width: 100%;
  }
  .el-dialog__body {
    padding-bottom: 10px !important;
  }
  .actionRed {
    color: red;
    font-weight: bold;
    font-size: 20px;
  }
  .el-textarea {
    .el-textarea__inner {
      height: 100px;
    }
  }
  .notice-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .notice-uploader .el-upload:hover {
    border-color: #1dc8a4;
  }
  .notice-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 200px;
    line-height: 200px;
    text-align: center;
  }
  .notice {
    width: 200px;
    height: 200px;
    display: block;
  }
  .el-upload__tip {
    margin-top: 0;
    color: #c0c4cc;
  }
}
</style>
